package com.junlong0716.enjoylearning.ui

import android.content.Intent
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.adapter.ChannelListAdapter
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.entity.AudioEntity
import com.junlong0716.enjoylearning.entity.ChannelMultipleItemEntity
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.getknowledgedemo.decoration.DividerItemDecoration
import com.junlong0716.module.common.base.BaseFragment
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import org.json.JSONObject

/**
 *@author: 巴黎没有摩天轮Li
 *@description:
 *@date: Created in 下午11:08 2018/5/23
 *@modified by:
 */
class ChannelDetailFragment : BaseFragment<ChannelDetailPresenter>(), ChannelDetailContract.View, BaseQuickAdapter.RequestLoadMoreListener {
    private var typeId = 0
    private var channelType = 0
    private lateinit var mSmartRefreshLayout: SmartRefreshLayout
    private var currentPage = 1
    private var onePageCount = 10
    private lateinit var rvList: RecyclerView
    private lateinit var channelListAdapter: ChannelListAdapter
    private lateinit var data: ArrayList<ChannelMultipleItemEntity>
    private var isLoadingMore = false

    override fun getLayoutId(): Int = R.layout.fragment_channel_detail

    override fun initViews(mRootView: View?) {
        data = ArrayList()
        mSmartRefreshLayout = mRootView!!.findViewById(R.id.srl_refresh)
        rvList = mRootView.findViewById(R.id.rv_list)
        mSmartRefreshLayout.isEnableLoadMore = false
        mSmartRefreshLayout.setOnRefreshListener {
            isLoadingMore = false
            currentPage = 1
            requestKnowledgeData()

        }
        rvList.layoutManager = LinearLayoutManager(activity)
        channelListAdapter = ChannelListAdapter(data)
        rvList.adapter = channelListAdapter
        channelListAdapter.setOnLoadMoreListener(this, rvList)
        rvList.addItemDecoration(DividerItemDecoration(activity!!.applicationContext, LinearLayoutManager.VERTICAL, 4, ContextCompat.getColor(activity!!, R.color.recyclerview_divider_gray)))
        channelListAdapter.setOnItemClickListener { adapter, view, position ->
            when (data[position].knowledgeType) {
                1 -> {
                    val intent = Intent()
                    intent.setClass(activity, VideoActivity::class.java)
                    intent.putExtra("video_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("video_id", data[position].id)
                    intent.putExtra("video_author", data[position].authorName)
                    startActivity(intent)
                }
                2 -> {
                    val parentActivity = activity as ChannelActivity
                    val audioEntity = AudioEntity(data[position].id,NetConstant.REQUEST_SOURCE+data[position].fileAddress,data[position].knowledgeTitle,NetConstant.REQUEST_SOURCE + data[position].coverImg)
                    parentActivity.getPlayerManager().playMusic(audioEntity)
                }
                3 -> {
                    val intent = Intent()
                    intent.setClass(activity, WebActivity::class.java)
                    intent.putExtra("document_url", NetConstant.REQUEST_SOURCE + data[position].fileAddress)
                    intent.putExtra("document_title", data[position].knowledgeTitle)
                    intent.putExtra("document_id", data[position].id)
                    activity!!.startActivity(intent)
                }
                else -> {

                }
            }
        }

        setOnRecyclerViewScrollDirectListener(rvList)
    }

    override fun onLoadMoreRequested() {
        isLoadingMore = true
        currentPage += 1
        requestKnowledgeData()
    }

    private fun requestKnowledgeData() {

        val map = HashMap<String, Any>()
        map["currentPage"] = currentPage
        map["onePageCount"] = onePageCount
        map["type"] = channelType
        if (typeId != 0) {
            map["classifyId"] = typeId
        }
        val jsonObj = JSONObject(map)
        OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_QUERY_KNOWLEDGE_LIST)
                .tag(this)
                .upJson(jsonObj)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        mSmartRefreshLayout.finishRefresh()
                        val jsonObject = JSONObject(response!!.body())
                        val code = jsonObject.getInt("code")
                        if (code == 200) {

                            if (isLoadingMore) {

                                val loadingMoreData = ArrayList<ChannelMultipleItemEntity>()

                                val data = jsonObject.getJSONObject("data")
                                val jsonArray = data.getJSONArray("list")
                                for (i in 0 until jsonArray.length()) {
                                    val id = jsonArray.getJSONObject(i).getInt("id")
                                    val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                                    val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                                    val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeContent")
                                    val knowledgeDescribe = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                                    val knowledgeAuthor = jsonArray.getJSONObject(i).getString("knowledgeAuthor")
                                    val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                                    val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                                    val browseNumber = jsonArray.getJSONObject(i).getString("browseNumber")
                                    val praiseNumber = jsonArray.getJSONObject(i).getInt("praiseNumber")
                                    val commentNumber = jsonArray.getJSONObject(i).getString("commentNumber")
                                    val specialId = jsonArray.getJSONObject(i).getString("specialId")
                                    val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                                    val remarks = jsonArray.getJSONObject(i).getString("remarks")
                                    val authorName = jsonArray.getJSONObject(i).getString("authorName")

                                    /*var id: Int, var knowledgeType: Int, var knowledgeTitle: String,
                                   var knowledgeContent: String, var knowledgeAuthor: String,
                                   var coverImg: String, var praiseNumber: Int,
                                   var fileAddress: String, var browseNumber: Int,
                                   var commentNumber: String, var specialId: Int,
                                   var createBy: String, var createDate: Long,
                                   var authorName: String*/
                                    loadingMoreData.add(ChannelMultipleItemEntity(id, knowledgeType, knowledgeTitle
                                            , knowledgeDescribe, knowledgeContent, knowledgeAuthor, coverImg, praiseNumber, fileAddress, browseNumber,
                                            commentNumber, specialId, createDate, authorName, ""))
                                }


                                if (loadingMoreData.isEmpty()) {
                                    channelListAdapter.loadMoreEnd()
                                    return
                                }
                                channelListAdapter.addData(loadingMoreData)
                                channelListAdapter.loadMoreComplete()


                            } else {
                                this@ChannelDetailFragment.data.clear()
                                val data = jsonObject.getJSONObject("data")
                                val jsonArray = data.getJSONArray("list")
                                for (i in 0 until jsonArray.length()) {
                                    val id = jsonArray.getJSONObject(i).getInt("id")
                                    val knowledgeType = jsonArray.getJSONObject(i).getInt("knowledgeType")
                                    val knowledgeTitle = jsonArray.getJSONObject(i).getString("knowledgeTitle")
                                    val knowledgeContent = jsonArray.getJSONObject(i).getString("knowledgeContent")
                                    val knowledgeDescribe = jsonArray.getJSONObject(i).getString("knowledgeDescribe")
                                    val knowledgeAuthor = jsonArray.getJSONObject(i).getString("knowledgeAuthor")
                                    val coverImg = jsonArray.getJSONObject(i).getString("coverImg")
                                    val fileAddress = jsonArray.getJSONObject(i).getString("fileAddress")
                                    val browseNumber = jsonArray.getJSONObject(i).getString("browseNumber")
                                    val praiseNumber = jsonArray.getJSONObject(i).getInt("praiseNumber")
                                    val commentNumber = jsonArray.getJSONObject(i).getString("commentNumber")
                                    val specialId = jsonArray.getJSONObject(i).getString("specialId")
                                    val createDate = jsonArray.getJSONObject(i).getLong("createDate")
                                    val remarks = jsonArray.getJSONObject(i).getString("remarks")
                                    val authorName = jsonArray.getJSONObject(i).getString("authorName")

                                    /*var id: Int, var knowledgeType: Int, var knowledgeTitle: String,
                                   var knowledgeContent: String, var knowledgeAuthor: String,
                                   var coverImg: String, var praiseNumber: Int,
                                   var fileAddress: String, var browseNumber: Int,
                                   var commentNumber: String, var specialId: Int,
                                   var createBy: String, var createDate: Long,
                                   var authorName: String*/
                                    this@ChannelDetailFragment.data.add(ChannelMultipleItemEntity(id, knowledgeType, knowledgeTitle
                                            , knowledgeDescribe, knowledgeContent, knowledgeAuthor, coverImg, praiseNumber, fileAddress, browseNumber,
                                            commentNumber, specialId, createDate, authorName, ""))
                                }
                                if (this@ChannelDetailFragment.data.isEmpty()) {
                                    channelListAdapter.emptyView = LayoutInflater.from(activity).inflate(R.layout.view_empty, null)
                                }
                                channelListAdapter.notifyDataSetChanged()
                                onLoadMoreRequested()
                            }
                        }


                    }
                })
    }


    override fun lazyFetchData() {
        typeId = arguments!!.getInt("typeId")
        channelType = arguments!!.getInt("channelType")
        mSmartRefreshLayout.autoRefresh()
    }

    override fun attachPresenter() {
        mPresenter = ChannelDetailPresenter()
        mPresenter!!.attachView(this)
    }

    //单例
    companion object {
        fun newInstance(channelType: Int, typeId: Int): ChannelDetailFragment {
            val bundle = Bundle()
            //获取分类ID
            bundle.putInt("typeId", typeId)
            //获取频道属性  视频 文稿 音乐
            bundle.putInt("channelType", channelType)
            val channelDetailFragment = ChannelDetailFragment()
            channelDetailFragment.arguments = bundle
            return channelDetailFragment
        }
    }


}